// Package sys
// @Link  https://github.com/bufanyun/hotgo
// @Copyright  Copyright (c) 2025 HotGo CLI
// @Author  Ms <133814250@qq.com>
// @License  https://github.com/bufanyun/hotgo/blob/master/LICENSE
// @AutoGenerate Version 2.15.11
package sys

import (
	"context"
	"github.com/gogf/gf/v2/frame/g"
	"github.com/gogf/gf/v2/util/gconv"
	"github.com/silenceper/wechat/v2/cache"
	"github.com/silenceper/wechat/v2/credential"
	"github.com/silenceper/wechat/v2/miniprogram/qrcode"
	"github.com/silenceper/wechat/v2/miniprogram/urllink"
	"hotgo/api/admin/usermodule"
	"hotgo/internal/library/storager"
	"hotgo/internal/library/wechat"
	"hotgo/internal/model/input/apiin"
	"hotgo/internal/model/input/sysin"
	"hotgo/internal/service"
)

var (
	UserModule = cUserModule{}
)

type cUserModule struct{}

// List 查看用户模块列表
func (c *cUserModule) List(ctx context.Context, req *usermodule.ListReq) (res *usermodule.ListRes, err error) {
	list, totalCount, err := service.SysUserModule().List(ctx, &req.UserModuleListInp)
	if err != nil {
		return
	}

	if list == nil {
		list = []*sysin.UserModuleListModel{}
	}

	res = new(usermodule.ListRes)
	res.List = list
	res.PageRes.Pack(req, totalCount)
	return
}

// Status 更新用户模块状态
func (c *cUserModule) Status(ctx context.Context, req *usermodule.StatusReq) (res *usermodule.StatusRes, err error) {
	err = service.SysUserModule().Status(ctx, &req.UserModuleStatusInp)
	return
}

// MiniProgramQrCode 获取小程序码
func (c *cUserModule) MiniProgramQrCode(ctx context.Context, req *usermodule.MiniProgramQrCodeReq) (res *usermodule.MiniProgramQrCodeRes, err error) {

	res = new(usermodule.MiniProgramQrCodeRes)
	res.MiniProgramQrCodeModel = new(apiin.MiniProgramQrCodeModel)

	// 获取小程序二维码
	miniProgram := wechat.NewMpPlatform(ctx)

	miniProgram.SetAccessTokenHandle(credential.NewDefaultAccessToken(
		wechat.GetConfig().OpenAppID, wechat.GetConfig().OpenAppSecret, credential.CacheKeyMiniProgramPrefix, cache.NewMemory()))

	envVersion := g.Cfg().MustGet(ctx, "system.envVersion", "trial").String()
	checkPath := gconv.PtrBool(false)
	if envVersion == "release" {
		checkPath = gconv.PtrBool(true)
	}
	qrCode, err := miniProgram.GetQRCode().GetWXACodeUnlimit(qrcode.QRCoder{
		Path:       req.Path,
		Page:       req.Path,
		Width:      req.Width,
		Scene:      req.Scene,
		IsHyaline:  req.IsHyaline,
		CheckPath:  checkPath,
		EnvVersion: g.Cfg().MustGet(ctx, "system.envVersion", "trial").String(),
	})
	if err != nil {
		return
	}

	drive := &storager.OssDrive{}
	fullPath, err := drive.UploadBytes(ctx, qrCode)
	if err != nil {
		return
	}

	res.QrCodeUrl = fullPath
	res.UrlLink, err = miniProgram.GetURLLink().Generate(&urllink.ULParams{
		Path:           req.Path,
		Query:          req.Scene,
		ExpireType:     1,
		ExpireInterval: 30,
		EnvVersion:     g.Cfg().MustGet(ctx, "system.envVersion", "trial").String(),
	})

	return
}
